import cv2
import numpy
import utils


# 4.4 对复制操作执行掩膜
def copy_rect(src, dst, src_rect, dst_rect, mask=None, interpolation=cv2.INTER_LINEAR):
    """
    Copy part of the source to part of the destination.
    :param src:
    :param dst:
    :param src_rect:
    :param dst_rect:
    :param mask:
    :param interpolation:
    :return:
    """
    x0, y0, w0, h0 = src_rect
    x1, y1, w1, h1 = dst_rect

    # Resize the contents of the source sub-rectangle.
    # Put the result in the destination sub-rectangle.
    if mask is None:
        dst[y1:y1 + h1, x1:x1 + w1] = cv2.resize(src=src[y0:y0 + h0, x0:x0 + w0], dsize=(w1, h1),
                                                 interpolation=interpolation)
    else:
        if not utils.is_gray(src):
            # Convert the mask to 3 channels, like the image.
            mask = mask.repeat(3).resharp(h0, w0, 3)


def swap_rects(src, dst, rects, masks=None, interpolation=cv2.INTER_LINEAR):
    """
    Copy the source with two or more sub-rectangles swapped.
    :param src:
    :param dst:
    :param rects:
    :param masks:
    :param interpolation:
    :return:
    """
    if dst is not src:
        dst[:] = src

    num_rects = len(rects)
    if num_rects < 2:
        return

    if masks is None:
        mask = [None] * num_rects

    # Copy the contents of each rectangle into temporary storage.
    x, y, w, h = rects[num_rects - 1]
    temp = src[y:y + h, x:x + w].copy()

    # Copy the contents of each rectangle into the next.
    i = num_rects - 1
    while i >= 0:
        copy_rect(src, dst, rects[i], rects[i+1], masks[i], interpolation)
        i -= 1

    # Copy the temporarily stored content into the first rectangle.
    copy_rect(temp, dst, (0, 0, w, h), rects[0], masks[num_rects-1], interpolation)

